import numpy as np
import matplotlib.pyplot as plt
from sklearn.svm import SVR
from sklearn.model_selection import GridSearchCV
from fpdf import FPDF

# 设置字体为支持中文的字体
plt.rcParams['font.family'] = 'SimHei'  # 或者使用 'AR PL UKai CN'
plt.rcParams['axes.unicode_minus'] = False  # 用于正常显示负号

# 示例数据
X = np.array([[0], [1], [2], [3], [4], [5], [6]])
y = np.array([0.5, 2, 3, 5, 7, 11, 17])

C_values = np.linspace(1, 20, 20)
epsilon_values = np.linspace(0.01, 5, 20)

param_grid = {
    'C': C_values,
    'epsilon': epsilon_values,
    'kernel': ['rbf']
}

grid_search = GridSearchCV(SVR(), param_grid, cv=5, scoring='neg_mean_squared_error')
grid_search.fit(X, y)

best_params = grid_search.best_params_
print(f"Best parameters: {best_params}")

# 创建SVR模型
svr = SVR(kernel='rbf', C=best_params['C'], epsilon=best_params['epsilon'])

# 训练模型
svr.fit(X, y)

# 预测
X_test = np.linspace(0, 6, 100).reshape(-1, 1)
y_pred = svr.predict(X_test)

# 可视化
plt.scatter(X, y, color='blue', label='数据点')
plt.plot(X_test, y_pred, color='red', label='SVR预测')
plt.xlabel('X')
plt.ylabel('y')
plt.legend()
plt.savefig('machine-svr.png')
plt.show()

# 创建 PDF 报告
pdf = FPDF()
pdf.add_page()
# 设置字体和大小
pdf.set_font("Arial", size=14)
# 添加文本
pdf.cell(200, 10, txt="Hello, this is my first PDF!", ln=True, align="C")
pdf.image("machine-svr.png", x=10, y=30,w=200)
pdf.output("machine-svr.pdf")